<!--聊天信息面板组件-->
<template>
<!--  <div >
    <h2>{{JSON.stringify(chatting.user)}}</h2>
    <br/>
    <p>{{JSON.stringify(chatting.chatter)}}</p>
  </div>-->
  <div class="flex flex-col h-full">
    <!--标题栏-->
    <div class="flex-none h-16 flex flex-row items-center gap-2 bg-orange-200 ">
      <!--头像-->
      <div class="avatar " :class="chatting.chatter.avatarUrl?'':'placeholder'">
        <div v-if="chatting.chatter.avatarUrl" class="rounded-full w-12">
          <img :src="chatting.chatter.avatarUrl" alt="Avatar" oncontextmenu="return false"/>
        </div>
        <div v-else class="bg-neutral text-neutral-content rounded-full w-12">
          <span class="text-lg">{{ chatting.showName.substring(0, 1).toUpperCase() }}</span>
        </div>
      </div>

      <div>
        {{ chatting.showName }}
      </div>
    </div>

    <!--对话展示区域-->
    <div class="grow h-full overflow-scroll " ref="containerRef">
<!--
      <VueEternalLoading :load="load" position="top" :container="containerRef" :is-initial="true"/>
-->

      <template v-for="item in chatting.messages">
        <MessageBubble :chatMsg="item"></MessageBubble>
      </template>
    </div>

    <!--消息输入区域-->
    <div class="flex-none h-36 bg-orange-200 p-2">
      <div class="bg-white rounded-lg p-2">
        <textarea v-model="inputText" placeholder="input ..." class="textarea textarea-bordered  w-full"></textarea>

        <div class="flex flex-row ">
          <div class="flex basis-1/2 gap-1 ">
            <button class="btn btn-sm " @click="() => {}">
              <IconEmoji/>
            </button>

            <button class="btn btn-sm " @click="() => {}">
              <IconFolder/>
            </button>

            <el-upload ref="elUploadRef"
                       :action="configStore.serverHost+'/file/upload/picture'"
                       multiple
                       :headers="fileHeaders"
                       :limit="5"
                       :accept="'image/*'"
                       :show-file-list="false"
                       :before-upload="beforeUpload"
                       :on-exceed="handleExceed"
                       :on-success="handleUploadSuccess" >
              <button class="btn btn-sm " @click="() => {elUploadRef.clearFiles()}">
                <IconPicture/>
              </button>
            </el-upload>
          </div>

          <div class="flex basis-1/2 gap-1 justify-end ">
            <button class="btn btn-sm btn-info w-20" @click="clickSend">
              <IconSend/>
            </button>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import {Chatting, ContactsItem} from '../../models/contacts.ts';
import {useChatStore} from "@/stores/chat.ts";
import {useConfigStore} from "@/stores/localconfig.js";
import {getTokenAtStorage} from "@/utils/tokens.js";
import {defineProps, onMounted, onUnmounted, ref, toRaw} from 'vue'
import IconPicture from "@/components/icons/IconPicture.vue";
import IconSend from "@/components/icons/IconSend.vue";
import IconFolder from "@/components/icons/IconFolder.vue";
import IconEmoji from "@/components/icons/IconEmoji.vue";
import 'element-plus/es/components/message/style/css';
import 'element-plus/es/components/message-box/style/css';
import 'element-plus/theme-chalk/el-upload.css'
import {ElMessage, ElUpload, type UploadProps} from 'element-plus'
import {Msg_Type} from "@/models/message.ts";
import MessageBubble from "@/views/chatting_components/MessageBubble.vue";

//父组件传值时的定义
const props = defineProps<{
  chatting: Chatting;
}>();

const configStore = useConfigStore();
const chatStore = useChatStore();

const clickAdd = ()=>{
  console.debug("clickAdd ...")
  console.log(props.chatting)
}

const clickVoice = () => {
  console.log(`clickVoice...`);

}
const clickVideo = () => {
  console.log(`clickVideo...`);
}


const containerRef = ref();

onMounted(() => {
  window.addEventListener('keydown', clickKeydown)
});
onUnmounted(() => {
  window.removeEventListener('keydown', clickKeydown, false)
})

// 定义 clickKeydown 函数，明确参数类型
const clickKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && (event.ctrlKey || event.shiftKey)) {
    event.preventDefault(); // 阻止默认事件
    inputText.value = inputText.value + '\n';
  } else if (event.key === 'Enter') {
    event.preventDefault(); // 阻止默认事件
    clickSend();
  }
};
/**
 * 文字消息相关
 */
//输入的文本框内容
const inputText = ref("");

/**
 * 检查参数
 * @param content
 * @param receiver
 * @returns {boolean}
 */
const checkArgument = (content:string, receiver:string):boolean => {
  console.debug("receiver = " + receiver)
  if (!receiver) {
    ElMessage.error("发生参数错误");
    console.warn("获取不到 receiver. 无法发生消息")
    return false;
  }

  if (!content) {
    console.warn("发送图片的链接不能为空");
    return false;
  }
  return true;
}

/**
 * 发送文本消息
 */
const clickSend = () => {
  console.debug("clickSend...")
  const receiver = getReceiver();

  if (checkArgument(inputText.value, receiver)) {
    if (sendMessage(inputText.value, Msg_Type.TEXT, receiver, props.chatting.isGroup)) {
      inputText.value = "";
    } else {
      ElMessage.error("消息发送失败");
    }
  }
  console.debug("clickSend end...")
}


/* 上传图片相关 */

/**
 * 发送图片消息
 * @param pictureUrl
 */
const sendPicture = (pictureUrl: string) => {
  console.debug("clickSend...")
  const receiver = getReceiver();

  if (checkArgument(pictureUrl, receiver)) {
    if (!sendMessage(pictureUrl, Msg_Type.PICTURE, receiver, props.chatting.isGroup)) {
      ElMessage.error("消息发送失败");
    }
  }
}

/**
 * 上次图片相关
 */
const elUploadRef = ref();

const fileHeaders = {
  // "Content-Type":"image/jpeg",
  "Authorization": `Bearer ${getTokenAtStorage()}`,
  "userType": "web",
  "appId": "fechatabc"
}
const handleExceed = (files:File[]) => {
  ElMessage.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件`);
}
const beforeUpload = (rawFile:File) => {
  const isPicture = (file:File):boolean => {
    return file.type.startsWith('image/');
  }
  const isLt10M = (file:File):boolean => {
    return file.size / (1024 * 1024) < 10;
  }
  console.log(">>> file type =  ", rawFile.type)

  if (!isPicture(rawFile)) {
    ElMessage.error('上传文件格式不对，只能选择图片');
    return false;
  }
  if (!isLt10M(rawFile)) {
    ElMessage.error('上传文件大小不能超过 10MB!');
    return false;
  }
  return true;
}

/**图片上传成功回调*/
const handleUploadSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  let pictureImage = URL.createObjectURL(uploadFile.raw!)
  console.log(">>> res = "+JSON.stringify(response))
  console.log(">>> pictureImage = ",pictureImage)

  if (response.ok) {
    let pictureUrl = response.data.split('?')[0]; //截取一下url
    console.debug(`pictureUrl = ${pictureUrl}`)
    sendPicture(pictureUrl);
  } else {
    ElMessage.error("上传图片失败!");
  }
}

const getReceiver = ():string =>{
  return props.chatting ? props.chatting.relId : (props.chatting.chatter as ContactsItem).userId;
}

function sendMessage(content: string, type: Msg_Type, receiver: string, isGroup = false):boolean {
  console.debug("sendMessage...")
  window.chatService.sendMessage(content, receiver, type, isGroup);
  // window.websocketClient.send('Hello from main process');
  return true
}

</script>

<style scoped lang="scss">

</style>
<script setup lang="ts">
</script>